
<template>
    <div id="my-charts">
        <div class="charts-container flex-center">
            <div id="v_charts" v-if="!relation">
                <my-v-charts :colors="colors" :chartData="chartData" :chartSettings="chartSettings" v-if="!relation"></my-v-charts>
            </div>
            <div style="width:100%;height:100%" v-if="relation">
                <e-charts :key="eKey" ref="eCharts" :orignData="option" @deleteNode="deleteNode" @addNode="addNode" @changeOrignData="changeOrignData"></e-charts>
            </div>
        </div>
        <div v-if="!chartsData" style="margin-bottom: 15px;">
            图表名称： <el-input style="width:300px" v-model="chartTitle" placeholder="请输入图表名称" @input="val=>title.name=val||titleName" @change="(val)=>editSetting.tableName=val" v-arouse></el-input>
        </div>
        <div class="flex-center">
            <div v-if="!chartsData">
                <span class="editHandle" @click="dialogVisible=true" v-if="!relation">
                    编辑数据
                </span>
                <span class="editHandle" @click="relationDialog=true" v-else>
                    编辑数据
                </span>
                <span class="editHandle" @click="saveCharts" style="margin-left:15px">
                    保存
                </span>
            </div>
            <span class="editHandle close_btn" @click="colseChartsDialog" v-else>
                关闭
            </span>
            <!-- <span class="editHandle" style="margin-left:15px" @click="saveCharts">
                保存图表
            </span> -->
        </div>
        <div class="charts-dialog flex-center" v-if="!relation&&dialogVisible">
            <div class="charts-dialog-container">
                <div class="title flex-between">
                    <span class="s-18">编辑数据</span>
                    <img class="close" src="../../../assets/img/close-table.png" alt="" @click="dialogVisible = false">
                </div>
                <div class="dialog-table">
                    <my-table :editSetting="JSON.parse(JSON.stringify(editSetting))" @closeDialog="closeDialog" @editChartsData="editChartsData"></my-table>
                </div>
            </div>
        </div>
        <div class="charts-dialog ra-dialog flex-center" v-if="relation&&relationDialog">
            <div class="ra-dialog-container align-between">
                <div class="title flex-between">
                    <span class="s-18">编辑数据</span>
                    <img class="close" src="../../../assets/img/close-table.png" alt="" @click="relationDialog = false">
                </div>
                <div class="relation-table flex-center">
                    <div class="ra-table-container">
                        <table class="ra-table">
                            <tr>
                                <td class="ra-item ra-item-root " style="position: relative;">
                                    <div class="name-tips-root flex-center">
                                        根节点名称
                                    </div>
                                    <div class="flex-end" v-if="showInput==='root'">
                                        <el-button style="margin-right:10px" type="text" size="mini" @click="cacheHandle(option[option.length-1])">取消</el-button>
                                        <el-button style="margin-right:10px" type="text" size="mini" @click="changeOrignData">确定</el-button>
                                        <el-input style="width:100px" v-arouse size="mini" v-model="option[option.length-1].focusName" placeholder="更改节点名称"
                                            @change="val=>optionChane(val,option.length-1,'focusName')">
                                        </el-input>
                                        <span style="color:#ccc">&nbsp;&nbsp;—— </span>
                                    </div>
                                    <div class="flex-end" v-else>
                                        <div class="root-content" @click="showInputhandle('root',option[option.length-1].focusName)">{{option[option.length-1].focusName}}</div>
                                        <span style="color:#ccc">&nbsp;&nbsp;—— </span>
                                    </div>
                                </td>
                                <!-- <td>
                            </td> -->
                            </tr>
                            <tr>
                                <td class="ra-item-root"></td>
                                <td>
                                    <table class="ra-table">
                                        <tr>
                                            <td>
                                                <div class="flex-center">
                                                    <!-- <span style="color:#ccc;opacity:0">&nbsp;&nbsp;——&nbsp;&nbsp;</span> -->
                                                    <span class="name-tips">节点名称</span>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="flex-center" style="padding-right: 70px;">
                                                    <span class="name-tips">关系名称</span>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr v-for="(item,index) in option" :key="item.id">
                                            <td class="ra-item" v-if="item.focusName===undefined">
                                                <div class="flex-start" v-if="showInput===item.id">
                                                    <span style="color:#ccc">——&nbsp;&nbsp;</span>
                                                    <el-input style="width:100px" v-arouse size="mini" v-model="item.contactName" placeholder="更改节点名称"
                                                        @change="val=>optionChane(val,index,'contactName')">
                                                    </el-input>
                                                    <span class="separate">-</span>

                                                </div>
                                                <div class="flex-start" v-else>
                                                    <span style="color:#ccc">——&nbsp;&nbsp;</span>
                                                    <div class="root-content" @click="showInputhandle(item.id,item.contactName)">{{item.contactName}}</div>
                                                    <span class="separate">-</span>
                                                </div>
                                            </td>
                                            <td v-if="item.focusName===undefined" class="ra-item">
                                                <div class="flex-start" v-if="showInput===item.id">
                                                    <!-- <el-input v-arouse size="mini" v-model="item.relation" placeholder="更改节点关系" @change="val=>optionChane(val,index,'relation')"></el-input> -->
                                                    <el-input style="width:100px" v-arouse size="mini" v-model="item.relation"  @change="val=>optionChane(val,index,'relation')" placeholder="更改节点关系"></el-input>
                                                    <el-button style="margin-left:10px" type="text" size="mini" @click="changeOrignData">确定</el-button>
                                                    <el-button style="margin-left:10px;" type="text" size="mini" @click="cacheHandle(item,index)">取消</el-button>
                                                </div>
                                                <div class="flex-start" v-else>
                                                    <div class="root-content" @click="showInputhandle(item.id,item.contactName)">
                                                        {{item.relation}}
                                                    </div>
                                                    <el-button style="margin-left:10px;color:#F56C6C;" type="text" size="mini" @click="deleteNode(index)">删除</el-button>
                                                    <el-button v-if="index===(option.length-2)" style="margin-left:10px;" type="text" size="mini" @click="addNode(index)">添加</el-button>
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </div>

                </div>
                <el-button style="margin-bottom:15px" type="primary" @click="relationDialog = false">确定</el-button>
            </div>
        </div>
        <el-dialog title="提示" :visible.sync="setChartsName" width="500px">
            <div class="flex-center">
                图表名称： <el-input v-model="chartTitle" placeholder="请输入图表名称" v-arouse style="width:300px"></el-input>
            </div>
            <div slot="footer">
                <el-button type="primary" @click="afterSetChartsName" :disabled="!chartTitle">确 定</el-button>
                <el-button @click="cancelSetName">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import myVCharts from './v-charts'
import ECharts from './echarts'
const nameMap = {
    // histogram: "柱状图",
    // line: '折线图',
    // pie: '饼图'
    histogram: "图表名称",
    line: '图表名称',
    pie: '图表名称'
}
export default {
    name: 'MyECharts',
    components: {
        myVCharts,
        ECharts,
    },
    props: {
        chartsData: {
            type: Object,
            default: null,
        },
        showChartsDialog: Boolean

    },
    inject: ['title'],
    data () {
        return {
            eKey: 1,
            chartTitle: '',
            dialogVisible: false,
            relationDialog: false,
            colors: ['#48AFFF', '#4ECB73', '#FBD437', '#FF9F03', '#F56C6C', '#F841A0', '#CE3FF7', '#833EF6'],
            chartData: {
                columns: [],
                rows: []
            },
            type: '',
            chartSettings: {
                // metrics: ['示例一', '示例二','示例三'],
                // dimension: ['示例'],
                type: 'histogram'
            },
            relation: false,
            //不最外层数据结构不在更改
            option: [
                {
                    "id": 0,
                    "contactName": '节点1',
                    "relation": "关系1"
                },
                {
                    "id": 1,
                    "contactName": "节点2",
                    "relation": "关系2"
                },
                {
                    "id": 2,
                    "contactName": "节点3",
                    "relation": "关系3"
                },
                {
                    "id": 3,
                    "contactName": '节点4',
                    "relation": "关系4"
                },
                {
                    "id": 'root',
                    "focusName": "根节点"
                }
            ],
            showInput: '',
            editSetting: {},
            titleName: '',
            setChartsName: false,
            filePath: ''//保存文件路径
        }
    },
    beforeCreate () {
        this.$options.components.MyTable = require('./MyTable.vue').default

    },
    created () {
        const { type } = this.chartsData || this.$route.params
        this.initCharts()
    },
    computed: {
        defaultChartName () {
            const chartsName = {
                histogram: "图表名称-柱状图",
                line: '图表名称-折线图',
                pie: '图表名称-饼图'
            }
            return chartsName[this.chartSettings.type]
        }
    },
    methods: {
        //取消操作
        cacheHandle (item, index) {
            if (this._isAdding && index !== undefined) {
                this._isAdding = false
                this.option.splice(index, 1)
            } else {
                if (item.id === 'root') {
                    item.focusName = this.focusName
                } else {
                    item.contactName = this.contactName
                }
            }

            this.showInput = ''
        },
        showInputhandle (id, name) {
            this.showInput = id
            if (id === 'root') {
                this.focusName = name
            } else {
                this.contactName = name
            }
        },
        optionChane (val, index, key) {
            if (!val) {
                 this.option[index][key] = (key === 'relation'? ' ' : this[key])
            }
        },
        changeOrignData () {
            this._isAdding = false
            this.showInput = ''
            this.eKey = this.eKey + 1
            // this.$refs.eCharts.updateChart(this.option)
        },
        deleteNode (index) {
            this.option.splice(index, 1)
            this.eKey = this.eKey + 1
        },
        addNode (index, param) {
            if (param) {
                let obj = {
                    id: index + 1,
                    contactName: param.name,
                    relation: param.ra
                }
                let pop = this.option.pop()
                this.option.push(...[obj, pop])
                this.changeOrignData()
            } else {
                let obj = {
                    id: index + 1,
                    contactName: `节点${index + 2}`,
                    relation: `关系${index + 2}`
                }
                let pop = this.option.pop()
                this.option.push(...[obj, pop])
                this._isAdding = true
                this.showInput = index + 1
            }

        },
        initCharts () {
            let tableColumn, rowData, type, tableData, tableName = null
            if (!this.chartsData) {
                //如果有originPath则是打开文件
                const originPath = this.filePath || this.$route.params.originPath
                let fileContent = null
                if (originPath) {
                    const fs = require('fs')
                    const path = require('path')
                    const fileRes = fs.readFileSync(originPath)
                    fileContent = JSON.parse(fileRes.toString())
                    // this.filePath = originPath
                }
                ({ tableColumn, rowData, type, tableData, tableName } = (fileContent || this.$route.params))
                //不是气泡图
                if (type !== 'relation') {
                    this.titleName = this.title.name = tableName || nameMap[type]
                } else {
                    //后续优化，没动力
                    if (fileContent) {
                        this.option = fileContent.option
                        this.titleName = this.title.name = fileContent.tableName
                    } else {
                        this.titleName = this.title.name = '图表名称'
                    }
                    this.relation = true
                }
                this.chartTitle = this.titleName
            } else {
                //表格弹框
                ({ tableColumn, rowData, type, tableData, tableName } = this.chartsData)
            }
            //全部用于表格回显，不做其他使用
            this.editSetting.tableColumn = tableColumn
            this.editSetting.rowData = rowData
            this.editSetting.tableData = tableData
            this.editSetting.tableName = tableName
            this.type = this.editSetting.type = type
            if (type === 'pie') {
                this.chartSettings.radius = window.innerWidth > 1440 ? 200 : 130
                this.chartSettings.offsetY = window.innerWidth > 1440 ? 300 : 240
            }
            if (type) {
                this.createChartsData(type, tableName)
            }
        },
        createChartsData (type, tableName) {
            if (!this.editSetting.tableColumn || !this.editSetting.rowData) return
            let columns = []
            let rows = []
            let keys = []
            this.editSetting.tableColumn.forEach((item, index) => {
                if (item.key) {
                    columns[index] = item.key
                    keys.push(item.key)
                } else {
                    columns[index] = 'rowKey'
                }
            })
            this.editSetting.rowData.forEach(row => {
                let obj = {
                    rowKey: row.rowKey
                }
                row.value.forEach((item, index) => {
                    if(item){
                        obj[keys[index]] = item.toString().replace(/^00*(?!\.)/g, '')
                    }
                })
                rows.push(obj)
            })
            this.chartData.rows = rows
            this.chartData.columns = columns
            this.chartSettings.type = type
            //图表标题
            this.chartTitle = tableName
        },
        saveCharts (cb) {
            if (!this.chartTitle) {
                this.setChartsName = true
                // this.$prompt('请输入图表名称', '提示', {
                //     confirmButtonText: '确定',
                //     cancelButtonText: '取消',
                // }).then(({ value }) => {
                //     this.chartTitle = value
                //     this.editSetting.tableName = value
                //     this.writeFile(cb)
                // })
            } else {
                this.writeFile(cb)
            }

        },
        //弹框输入名称后调用
        afterSetChartsName () {
            this.setChartsName = false
            this.editSetting.tableName = this.chartTitle
            this.writeFile()
        },
        cancelSetName () {
            this.chartTitle = ''
            this.setChartsName = false
        },
        writeFile (cb) {
            const fs = require('fs')
            let editSetting = this.editSetting
            let originPath = this.filePath
            if (originPath) {
                // const nameReg = /(?<=charts\\).*(?=_b_s_c_)/
                // const tiemReg = /(?<=_b_s_c_)\d+/
                // let newPath = originPath.replace(nameReg, this.tableName)
                // newPath = newPath.replace(tiemReg, new Date().getTime())
                if (fs.existsSync(originPath)) {
                    fs.unlinkSync(originPath)
                }
                // this.filePath = editSetting.originPath = newPath
                // fs.writeFileSync(newPath, new Uint8Array(Buffer.from(JSON.stringify(editSetting))))
            }
            const path = require('path')
            let filePath = ''
            let res = null
            if (this.relation) {
                const fileData = {
                    tableName: this.chartTitle,
                    option: this.option,
                    type: 'relation'
                }
                //关系图
                filePath = path.join(window.$DATADIR, 'resc', 'user', 'charts', this.chartTitle + '_b_s_c_' + Date.now() + 'r' + '.json')
                res = fs.writeFileSync(filePath, new Uint8Array(Buffer.from(JSON.stringify(fileData))))
            } else {
                editSetting.type = this.type
                filePath = path.join(window.$DATADIR, 'resc', 'user', 'charts', this.chartTitle + '_b_s_c_' + Date.now() + this.type.substr(0, 1) + '.json')
                res = fs.writeFileSync(filePath, new Uint8Array(Buffer.from(JSON.stringify(editSetting))))
            }
            this.filePath = filePath //用来标志是否保存过文件
            if (!res) {
                this.$message.success('保存成功')
                this._isChange = false
                console.log(cb);
                console.log('cb↑');
                // if (cb) {
                //     cb 
                // }
            }
        },
        editChartsData (editSetting) {
            this.editSetting = editSetting
            this.createChartsData(this.editSetting.type, this.editSetting.tableName)
            // this.saveCharts()
            this._isChange = true
            this.closeDialog()
        },
        closeDialog () {
            this.dialogVisible = false
        },
        colseChartsDialog () {
            // this.saveCharts()
            this.$emit('update:showChartsDialog', false)
        }
    },
    beforeRouteLeave (from, to, next) {
        if (this._isChange) {
            this.$confirm('是否保存修改?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(_ => {
                this.saveCharts(next)
            }).catch(_ => {
                next()
            })
        } else {
            next()
        }
    }
}
</script>

<style lang="scss" scope>
#my-charts {
    width: 1920px;
    height:800px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    .editHandle {
        display: inline-block;
        color: #fff;
        width: 100px;
        height: 40px;
        background: #4894ff;
        border-radius: 8px;
        line-height: 40px;
        text-align: center;
        margin-bottom: 20px;
        cursor: pointer;
    }
}
.charts-container {
    width: 100%;
    flex: 1;
    #v_charts {
        width: 95%;
        height: 95%;
        // width: 1726px;
        // height: 700px;
        // position: absolute;
        // top: -20px;
        // left: 85px;
    }
}
.charts-dialog {
    position: fixed;
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
    z-index: 100;
    background-color: rgba(#000, 0.4);
    .charts-dialog-container {
        min-width: 50vw;
        min-height: 40vh;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
    }
    .dialog-table {
        flex: 1;
        max-height: 80vh;
        overflow: scroll;
        padding: 10px 0;
    }
    .title {
        background: #f4f4f4;
        padding: 0 25px;
        height: 45px;
    }
    .close {
        width: 14px;
        height: 15px;
        cursor: pointer;
    }
}
.ra-table-container{
   transform: translateY(70px); 
}
.ra-dialog {
    .ra-dialog-container {
        min-width: 40vw;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        .title {
            width: 100%;
        }
    }
    .relation-table {
        min-height: 40vh;
        max-height: 60vh;
        width: 100%;
        overflow: scroll;
    }
    .ra-table {
        border-collapse: collapse;
        transform: translateY(-40px);
    }
    .ra-item {
        height: 50px;
        line-height: 40px;
        padding: 0 15px;
        cursor: pointer;
        padding: 5px 0;
    }
    .ra-item-root {
        border-right: 2px #ccc solid;
    }
    .ra-item-children {
        border-left: 2px #ccc solid;
        height: 30px;
        line-height: 30px;
    }
}
.name-tips {
    font-size: 14px;
    color: gray;
    font-weight: 900;
}
.name-tips-root {
    font-size: 14px;
    color: gray;
    position: absolute;
    top: -35px;
    right: 0;
    width: 175px;
    font-weight: 900;
    // background-color: rgba(#ccc, 0.4);
}
.root-content {
    width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: center;
    box-shadow: 5px 5px 5px 1px #ccc;
    border-radius: 4px;
    height: 40px;
}
.separate {
    margin: 0 15px;
}
 @media screen and (max-width: 1600px){
    #my-charts{
        width: 100vw;
        height:650px;
        .charts-container {
            width: 100%;
            flex: 1;
            // #v_charts {
            //     width: 90%;
            //     height: 90%;
            //     position: absolute;
            //     top: -20px;
            //     left: 80px;
            // }
        }
    }
 }
</style>
